/*
 * SFTPClientListener.cpp
 *
 *  Created on: Apr 10, 2011
 *      Author: sms103
 */

#include "SFTPClientListener.h"

SFTPClientListener::SFTPClientListener(SFTPClient *cli) {

	sftpClient=cli;//save pointer to Client obj

	//set the parameters for this listener from defaults/param file
	setParams();

	//create socket and bind to our listen port..
	listenSock = new TCPSocket();
	listening = listenSock->tcpBind(clientListenPort);
	if(!listening){
		cout<<"Error binding port "<<clientListenPort<<"."<<endl;
		return;
	}

	//listen on the socket
	listening = listenSock->tcpListen();
	if(!listening){
		cout<<"error listening on Client listen socket."<<endl;
		return;
	}


}

bool SFTPClientListener::isListening(){
	return listening;
}

void SFTPClientListener::close(){
	listening=false;

	listenSock->tcpClose();
}

void SFTPClientListener::runListener(){
	TCPSocket *newSock;

	LocalConnectionHandler *newHandler;

	while(1){
		//this ClientListener object has been asked to exit
		if(!listening){
			break;
		}

		//wait for conn
		newSock = listenSock->tcpAccept(200);

		if(newSock){//if newSock isnt null we have a new connection
			//create new session handler
			cout << "received connection from php."<<endl;
			newHandler = new LocalConnectionHandler(sftpClient,newSock);
			newHandler->handleConnection();
			delete(newHandler);
		}


	}
}

void SFTPClientListener::setParams(){
	//set port num
	sftpClient->paramParser->setIntParam(&clientListenPort,"clientListenPort",DEFAULT_CLIENT_LISTEN_PORT);

}


SFTPClientListener::~SFTPClientListener() {
	// TODO Auto-generated destructor stub
}
